package com.liutaw.nanjingair.models.datalayer;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by liutao on 16/3/13.
 */
public class NetWorkSource<T> {
    private String mUrl;
    private INetWorkHandler handler;
    private NetWorkSource() {

    }

    private String getUrl() {
        return mUrl;
    }

    private void setUrl(String mUrl) {
        this.mUrl = mUrl;
    }

    public INetWorkHandler getHandler() {
        return handler;
    }

    public void setHandler(INetWorkHandler handler) {
        this.handler = handler;
    }

    public void sendRequest(final java.lang.reflect.Type type) {
        final OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(this.getUrl()).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
//TODO请求出错的情况
               handler.onFailed(e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String out = response.body().string();
                    System.out.println(out);
//                    java.lang.reflect.Type type = new TypeToken<T>(){}.getType();
                    T item = (T) new Gson().fromJson(out, type);
//                    T data=null;
//                    T item = getObject(out,data.getClass());
                    if (item==null){
                        handler.onFailed(type.getClass().getSimpleName()+"对象解析出错，为null!");
                        return;
                    }
                   handler.onSucess(item);
                } else {
//                    notifyFailed("请求出错啦");
                    handler.onFailed(response.message());
                }
            }
        });
    }

    public void cancel() {

    }
//    private T getObject(String out,Class<T> clazz) {
//        T item = new Gson().fromJson(out, clazz);
//        return item;
//    }

    public static class Builder<T> {
        private NetWorkSource<T> netWorkSource;

        public Builder(String url) {
            netWorkSource = new NetWorkSource<T>();
            netWorkSource.setUrl(url);
        }

        public Builder buildCallBack(INetWorkHandler handler) {
            netWorkSource.setHandler(handler);
            return this;
        }
        public  NetWorkSource build() {
            return netWorkSource;
        }
    }


    public interface INetWorkHandler<T> {
        void onSucess(T data);
        void onFailed(String data);
    }

}
